// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

const rp = require('request-promise')

const URL = 'http://musicapi.xiecheng.live/personalized'

const db = cloud.database()

const playCollection = db.collection('playlist')

const MAX_LIMIT = 10

// 云函数入口函数
exports.main = async(event, context) => {
  // const list = await playCollection.get()
  // 对请求做出处理，微信对请求数据长度有限制，为查重做准备
  const countRequest = await playCollection.count()
  const total = countRequest.total
  const batchTimes = Math.ceil(total / MAX_LIMIT)
  const tasks = []
  for (let i = 0; i < batchTimes.length; i++) {
    let promise = playCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT)
    tasks.push(promise)
  }
  let list = {
    data: []
  }
  if (tasks.length > 0) {
    list = (await Promise.all(tasks)).reduce(acc, cur => {
      return {
        data: acc.data.concat(cur.data)
      }
    })
  }
  console.log(list.data)
  
  const playlist = await rp(URL).then(res => {
    return JSON.parse(res).result
  })
  // console.log(playlist)
  const newData = []
// 对集合里面和获取到的数据进行查重
  for (let i = 0, len1 = playlist.length; i < len1; i++) {
    let flag = true
    for (let j = 0, len2 = list.data.length; j < len2; j++) {
      if (playlist[i].id === list.data[j].id) {
        flag = false
        break
      }
    }
    if (flag) {
      newData.push(playlist[i])
    }
  }
// 将获取到的数据查重后储存到集合里面
  for (let i = 0, len = newData.length; i < len; i++) {
    await playCollection.add({
      data: {
        ...newData[i],
        createTimes: db.serverDate()
      }
    }).then(res => {
      console.log('插入成功')
    }).catch(err => {
      console.log('插入失败')
      console.log(newData.length)
    })
  }
  return newData.length
}
